package 力扣日常刷题.木22二月.第16天222;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author 帅小伙
 * @date 2022/2/22
 * @description
 */
public class Demo128滑动窗口的最大值 {


    /*
     * 单调上升的队列
     * 存储坐标
     * 利用坐标限制范围
     * */
    public int[] maxSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        if (n == 0) return new int[0];
        Deque<Integer> d = new LinkedList<>();
        for (int i = 0; i < k; i++) {
            while (!d.isEmpty() && nums[d.peekLast()] <= nums[i]) d.pollLast();
            d.addLast(i);
        }
        int[] ans = new int[n + 1 - k];
        ans[0] = nums[d.peekFirst()];
        for (int i = k; i < n; i++) {
            // if(nums[i - 1] == d.peekFirst()) d.pollFirst();
            while (!d.isEmpty() && nums[d.peekLast()] <= nums[i]) d.pollLast();
            d.offerLast(i);
            while (d.peekFirst() <= i - k) d.pollFirst();
            ans[i - k + 1] = nums[d.peekFirst()];
        }
        return ans;
    }

}
